package com.uenpay.im.ui.old.activity.dynamic;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.cache.HttpStreamCache;
import com.qiyunxin.android.http.common.ImageUtil;
import com.qiyunxin.android.http.listener.OnUploadFileListener;
import com.qiyunxin.android.http.net.HttpRequestAsyncTaskQueue;
import com.qiyunxin.android.http.net.HttpUploadFileAsyncTask;
import com.qiyunxin.android.http.utils.FileUtils;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.weight.choosemorepic.PhotoItem;
import com.qyx.android.weight.view.MyGridView;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.CameraActivity;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.choosemorepic.PhotoActivity;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.ImageSize;
import com.uenpay.im.weight.BottomDialog;
import com.uenpay.im.weight.MyDialog;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

/**
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */

public class SendDynamicActivity extends BaseActivity implements OnClickListener {
	private TextView textCount;
	private EditText send_text_et;
	private FileUtils fileUtils = new FileUtils(IMApplication.appName);
	private static final int PAIS = 3;
	private static final int PIC = 4;
	private ArrayList<String> showPics = new ArrayList<String>();
	private ArrayList<String> sendSuccessPics = new ArrayList<String>();
	private ArrayList<String> sendFailedPics = new ArrayList<String>();
	private View loading;
	private ArrayList<FileMessage> fileMessages = new ArrayList<FileMessage>();
	private String mStrContent = "";
	private String mStrShareImgPath = "";
	private String mStrShareTextContent = "";
	private ArrayList<PhotoItem> select_gl_arr = new ArrayList<PhotoItem>();
	private int mIntSelectPicCount;
	private ArrayList<ImageSize> size = new ArrayList<ImageSize>();
	private MyGridView pic_gd;
	private SendDynamicPicAdapter dynamicPicAdapter;

	private Handler handler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {

			switch (msg.what) {
				case 0:
					setPicGd();
					break;
				case 1:
					sendDynamic();
					break;
				case 4:
					if (loading != null) {
						loading.setVisibility(View.GONE);
					}
					break;
			}

			return false;
		}
	});

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isFullScreen = true;
		super.onCreate(savedInstanceState);
	}

	@Override
	public View bindView() {
		return null;
	}

	@Override
	public int bindLayout() {
		return R.layout.activity_send_friend_dynamic;
	}

	@Override
	public void initView(View view) {
		if (fileMessages != null) {
			fileMessages.clear();
		}
		Intent intent = getIntent();
		if (intent.getExtras() != null) {
			if (!TextUtils.isEmpty(intent.getStringExtra("textContent"))) {
				mStrShareTextContent = intent.getStringExtra("textContent");
			} else if (!TextUtils.isEmpty(intent.getStringExtra("imagePath"))) {
				mStrShareImgPath = intent.getStringExtra("imagePath");
			}
		}
		initView();
		initListener();
		if (!TextUtils.isEmpty(mStrShareTextContent)) {
			send_text_et.setText(mStrShareTextContent);
		} else if (!TextUtils.isEmpty(mStrShareImgPath)) {
			showPics.add(mStrShareImgPath);
			mIntSelectPicCount++;
		}
		setPicGd();
	}

	protected void initView() {
		((TextView) findViewById(R.id.title_textview)).setText(R.string.send_dynamic);
		((TextView) findViewById(R.id.title_right_tv)).setText(R.string.send);
		findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
		send_text_et = (EditText) findViewById(R.id.send_text_et);
		textCount = (TextView) findViewById(R.id.textCount);
		pic_gd = (MyGridView) findViewById(R.id.pic_gd);
		loading = findViewById(R.id.loading);
	}

	protected void initListener() {
		findViewById(R.id.back_layout).setOnClickListener(this);
		findViewById(R.id.title_right_layout).setOnClickListener(this);

		send_text_et.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				int number = 400 - s.length();
				if (number >= 0) {
					textCount.setText("" + number);
				}
			}
		});

	}

	OnClickListener showPicDialogListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			showPicDialog();
		}
	};

	private void setPicGd() {
		for (int i = 0, size = showPics.size(); i < size; i++) {
			if (showPics.get(i).equals("")) {
				showPics.remove(i);
				break;
			}
		}
		if (showPics.size() < 9) {
			showPics.add(showPics.size(), "");
		}
		if (dynamicPicAdapter == null) {
			dynamicPicAdapter = new SendDynamicPicAdapter(SendDynamicActivity.this, showPics, showPicDialogListener, new SendDynamicPicAdapter.IDeleteListener() {

				@Override
				public void onDelete(int index) {
					delImg(showPics.get(index), index);
				}
			});
			pic_gd.setAdapter(dynamicPicAdapter);
		} else {
			dynamicPicAdapter.setData(showPics);
		}
	}

	public void onClick(View v) {
		int i = v.getId();
		if (i == R.id.back_layout) {
			back();

		} else if (i == R.id.title_right_layout) {
			mStrContent = send_text_et.getText().toString();
			Utils.hideSoftKeyboard(send_text_et);

			if (showPics.size() > 0) {
				loading.setVisibility(View.VISIBLE);
				findViewById(R.id.title_right_layout).setEnabled(false);
				uploadPic(showPics);
			} else {
				if (!TextUtils.isEmpty(mStrContent)) {
					loading.setVisibility(View.VISIBLE);
					findViewById(R.id.title_right_layout).setEnabled(false);
					sendDynamic();
				} else {
					IMApplication.showToast(R.string.no_content);
				}
			}


		} else {
		}
	}

	protected void showPicDialog() {
		BottomDialog.showBottomDialog(SendDynamicActivity.this, getResources().getString(R.string
                .take_photo), getResources().getString(R.string.take_image), getResources()
                .getString(R.string.cancel), -1, new IOnBottomDialogListener() {

			@Override
			public void onClicked() {
				size.clear();
				Intent getImageByCamera = new Intent(SendDynamicActivity.this, CameraActivity
                        .class);
				size.add(new ImageSize(720, 720, ""));
				Bundle bundle = new Bundle();
				bundle.putSerializable("size", size);
				getImageByCamera.putExtras(bundle);
				startActivityForResult(getImageByCamera, PAIS);
			}
		}, new IOnBottomDialogListener() {

			@Override
			public void onClicked() {
				Bundle bundle = new Bundle();
				bundle.putInt("selected_count", mIntSelectPicCount);
				bundle.putInt("max_select_count", 9);
				ActivityHandle.startActivity(SendDynamicActivity.this, PhotoActivity.class,
                        bundle, PIC);
			}
		});

	}

	public void uploadPic(final ArrayList<String> list) {
		String url = APIConfiguration.getBaseUrl() + "Dynamic/Dynamic/sendFile?" +
                APIConfiguration.getCustIdAndToken();
		for (int i = 0; i < list.size(); i++) {
			String imgUrl = list.get(i);
			if (imgUrl.startsWith("http")) {
				imgUrl = HttpStreamCache.getInstance().GetFilePath(imgUrl);
			}

			HttpRequestAsyncTaskQueue.getInstance().AddTask(new HttpUploadFileAsyncTask(String
                    .valueOf(i), imgUrl, url, "uploadedFile") {

			}, new OnUploadFileListener() {

				@Override
				public void OnSuccess(String key, String response) {
					sendSuccessPics.add(list.get(Integer.valueOf(key)));
					FileMessage fileMessage = new FileMessage();
					try {
						JSONObject json = new JSONObject(response);
						fileMessage.status = json.optInt("status");
						JSONObject dataJson = json.optJSONObject("data");
						if (dataJson != null) {
							fileMessage.fileid = dataJson.optString("fileid");
							fileMessage.filehash = dataJson.optString("filehash");
							if (fileMessage != null && fileMessage.status == HttpInvokeResultCode
                                    .RESULT_OK) {
								fileMessages.add(fileMessage);
							}

						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
					if ((sendSuccessPics.size() + sendFailedPics.size()) == showPics.size()) {
						handler.sendEmptyMessage(1);
					}
				}

				@Override
				public void OnFail(String key, String reason) {
					sendFailedPics.add(list.get(Integer.valueOf(key)));

					if ((sendSuccessPics.size() + sendFailedPics.size()) == showPics.size()) {
						handler.sendEmptyMessage(1);
					}
				}
			});
		}

	}

	public void sendDynamic() {
		DynamicHandle mDynamicHandle = new DynamicHandle();
		mDynamicHandle.sendDynamic(mStrContent, fileMessages, null, null, new DynamicHandle
                .IDynamicResult() {

			@Override
			public void onDynamicResult(int status, String msg) {
				handler.sendEmptyMessage(4);
				if (!TextUtils.isEmpty(msg)) {
					IMApplication.showToast(msg);
				}
				findViewById(R.id.title_right_layout).setEnabled(true);
				if (status == HttpInvokeResultCode.RESULT_OK) {
					setResult(RESULT_OK);
					finish();
				}
			}
		});

	}

	public void delImg(final String pos, final int position) {

		MyDialog.Builder alertDialog = new MyDialog.Builder(SendDynamicActivity.this);
		alertDialog.setTitle(R.string.dialog_title);
		alertDialog.setMessage(getResources().getString(R.string.confirm_delete_image));
		alertDialog.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				showPics.remove(pos);
				mIntSelectPicCount--;
				handler.sendEmptyMessage(0);
			}
		});

		alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		alertDialog.create().show();

	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {

			if (data == null) {
				return;
			}

			File compressFile = null;
			Bitmap compressBitmap = null;
			switch (requestCode) {
				case PAIS:
					try {
						String strPicPath = data.getStringExtra("big_pic_filename");

						showPics.add(strPicPath);
						mIntSelectPicCount++;
						handler.sendEmptyMessage(0);

					} catch (Exception e) {
						e.printStackTrace();
					}
					break;
				case PIC:
					try {
						select_gl_arr.clear();
						select_gl_arr = (ArrayList<PhotoItem>) data.getSerializableExtra("gl_arr");

						if (select_gl_arr.size() > 0) {
							mIntSelectPicCount += select_gl_arr.size();
							for (int i = 0; i < select_gl_arr.size(); i++) {

								String path = select_gl_arr.get(i).getPath();

								compressFile = new File(fileUtils.getAlbumDir(), Utils.md5(path) +
                                        ".jpg");

								compressBitmap = ImageUtil.CompressImage(path, 960, 960);
								FileOutputStream fos;
								fos = new FileOutputStream(compressFile);
								compressBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
								String strPicPath = compressFile.getAbsolutePath();
								showPics.add(strPicPath);

							}

							handler.sendEmptyMessage(0);
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
					break;
				default:
					break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void back() {
		Utils.hideSoftKeyboard(send_text_et);
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				if (!TextUtils.isEmpty(send_text_et.getText().toString().trim()) || showPics.size
                        () > 0) {
					showDialog();
				} else {
					finish();
				}
			}
		}, 300);
	}

	public void showDialog() {
		MyDialog.Builder alertDialog = new MyDialog.Builder(SendDynamicActivity.this);
		alertDialog.setTitle(R.string.students_dynamic);
		alertDialog.setMessage(getResources().getString(R.string.giveup_edit));
		alertDialog.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				finish();
			}
		});

		alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		alertDialog.create().show();

	}

	@Override
	public void onBackPressed() {
		back();
	}
}
